<template>
  <el-dialog
    v-model="dialogVisible"
    :title="dialogFormId ? '编辑菜单' : '新增菜单'"
    width="700px"
    :append-to-body="true"
    :destroy-on-close="true"
    :before-close="onCancel"
    align-center
  >
    <template #default>
      <el-form
        ref="dialogRef"
        :model="dialogForm"
        :rules="formRules"
        label-width="100px"
        class="form"
      >
        <el-form-item v-if="dialogForm.type != 0" label="上级菜单" prop="parentId">
          <el-tree-select
            v-if="!isForst"
            placeholder="请选择上级菜单"
            style="width: 100%"
            v-model="dialogForm.parentId"
            :data="permission.treeList"
            :props="permission.treeProps"
            :render-after-expand="false"
            :check-strictly="true"
            value-key="id"
            @change="toggleTreeChecked"
          />
        </el-form-item>
        <el-form-item label="菜单名称" prop="name">
          <el-input v-model="dialogForm.name" placeholder="请输入菜单名称" />
        </el-form-item>
        <!--权限字符-->
        <el-form-item class="inline" prop="perms">
          <template #label>
            <el-tooltip
              effect="dark"
              content="控制器中定义的权限字符，如：@PreAuthorize(`@ss.hasPerm('system:user:list')`)"
              placement="top"
            >
              <div class="center">
                <span class="l-4">权限字符</span>
              </div>
            </el-tooltip>
          </template>
          <el-input v-model="dialogForm.perms" placeholder="请输入权限标识" />
        </el-form-item>
        <!--显示排序-->
        <el-form-item label="显示排序" prop="sort" class="inline">
          <el-input-number v-model="dialogForm.sort" :min="1" style="width: 100%" />
        </el-form-item>
        <!--全局状态-->
        <el-form-item prop="enabled" class="inline">
          <template #label>
            <el-tooltip
              effect="dark"
              content="选择停用则路由将不会出现在侧边栏，也不能被访问"
              placement="top"
            >
              <div class="center">
                <span class="l-4">状态</span>
              </div>
            </el-tooltip>
          </template>
          <el-radio-group v-model="dialogForm.enabled">
            <el-radio
              v-for="item in dicts.system_global_status"
              :key="item.v"
              :label="dialogForm.enabled == item.v ? dialogForm.enabled : item.v"
              >{{ item.k }}</el-radio
            >
          </el-radio-group>
        </el-form-item>
        <el-form-item label="菜单类型" prop="type">
          <el-radio-group v-model="dialogForm.type" @change="cutChange">
            <el-radio :label="0">目录</el-radio>
            <el-radio :label="1">菜单</el-radio>
            <el-radio :label="2">按钮</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--目录-->
        <div v-if="dialogForm.type == 0">
          <!--菜单图标-->
          <el-form-item label="菜单图标" prop="meta.icon" class="inline">
            <sc-icon-select v-model:modelValue="dialogForm.icon" clearable></sc-icon-select>
          </el-form-item>
          <!--路由地址-->
          <el-form-item prop="path" class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="访问的路由地址，如：`/system/user`，如外网地址需内链访问则以`http(s)://`开头"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">路由地址</span>
                </div>
              </el-tooltip>
            </template>
            <el-input v-model="dialogForm.path" placeholder="请输入路由地址" />
          </el-form-item>
          <!--是否外联-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择是外链则路由地址需要以`http(s)://`开头"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否外链</span>
                </div>
              </el-tooltip>
            </template>
            <el-radio-group v-model="dialogForm.outerChain">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <!--重定向地址-->
          <el-form-item prop="redirect" label="重定向地址" class="inline">
            <el-input v-model="dialogForm.redirect" placeholder="请输入重定向的地址" />
          </el-form-item>
          <!--是否显示-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否显示</span>
                </div>
              </el-tooltip>
            </template>
            <el-radio-group v-model="dialogForm.visible">
              <el-radio
                v-for="item in dicts.system_global_visibility"
                :key="item.v"
                :label="dialogForm.visible == item.v ? dialogForm.visible : item.v"
                >{{ item.k }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
        </div>
        <!--菜单-->
        <div v-if="dialogForm.type == 1">
          <!--菜单图标-->
          <el-form-item label="菜单图标" prop="meta.icon">
            <sc-icon-select v-model:modelValue="dialogForm.icon" clearable></sc-icon-select>
          </el-form-item>
          <!--路由地址-->
          <el-form-item prop="path" class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="访问的路由地址，如：`/system/user`，如外网地址需内链访问则以`http(s)://`开头"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">路由地址</span>
                </div>
              </el-tooltip>
            </template>
            <el-input v-model="dialogForm.path" placeholder="请输入路由地址" />
          </el-form-item>
          <!--重定向地址-->
          <el-form-item prop="redirect" label="重定向地址" class="inline">
            <el-input v-model="dialogForm.redirect" placeholder="请输入重定向的地址" />
          </el-form-item>
          <!--路由参数-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="访问路由的默认传递参数，如：`{id: 1, name: 'ry'}`"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">路由参数</span>
                </div>
              </el-tooltip>
            </template>
            <el-input v-model="dialogForm.query" placeholder="请输入路由参数" />
          </el-form-item>
          <!--是否缓存-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择是则会被`keep-alive`缓存，需要匹配组件的`name`和地址保持一致"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否缓存</span>
                </div>
              </el-tooltip>
            </template>
            <el-radio-group v-model="dialogForm.cache">
              <el-radio v-for="item in dicts.system_global_cache" :key="item.v" :label="item.v">{{
                item.k
              }}</el-radio>
            </el-radio-group>
          </el-form-item>
          <!--是否显示-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择隐藏则路由将不会出现在侧边栏，但仍然可以访问"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否显示</span>
                </div>
              </el-tooltip>
            </template>
            <el-radio-group v-model="dialogForm.visible">
              <el-radio
                v-for="item in dicts.system_global_visibility"
                :key="item.v"
                :label="item.v"
                >{{ item.k }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <!--是否外联-->
          <el-form-item class="inline">
            <template #label>
              <el-tooltip
                effect="dark"
                content="选择是外链则路由地址需要以`http(s)://`开头"
                placement="top"
              >
                <div class="center">
                  <span class="l-4">是否外链</span>
                </div>
              </el-tooltip>
            </template>
            <el-radio-group v-model="dialogForm.outerChain">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </el-form-item>
          <!--布局方式-->
          <el-form-item label="布局方式" class="inline" prop="parentView">
            <el-select
              placeholder="请选择布局方式"
              v-model="dialogForm.parentView"
              style="width: 100%"
            >
              <el-option
                v-for="item in dicts.system_menu_parentview"
                :key="item.v"
                :label="item.k"
                :value="item.v"
              />
            </el-select>
          </el-form-item>
          <!--组件路径-->
          <el-form-item label="组件路径" class="inline" prop="component">
            <el-input v-model="dialogForm.component" placeholder="请输入组件路径" />
          </el-form-item>
        </div>
      </el-form>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onCancel">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import {
  ref,
  reactive,
  onBeforeMount,
  getCurrentInstance,
  ComponentInternalInstance,
  toRefs
} from 'vue'
import { MenuItemForm } from '@interface/menu'
import { menuInfo, menuAdd, menuUpdata } from '@api/menu'
import { IRoleMenuItem, menuTree } from '@api/role'

import { ElMessage, ElMessageBox } from 'element-plus'
import normalizeMenuList from './normalizeMenuList'
const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false
  },
  dialogFormId: {
    type: String,
    default: ''
  }
})
//关闭dialog
// eslint-disable-next-line vue/valid-define-emits
const emit = defineEmits()
const dialogVisible = ref(props.dialogVisible)
const dialogFormId = ref(props.dialogFormId)
interface IPermission {
  treeList: IRoleMenuItem[]
  treeProps: {
    label: string
  }
  linkage: boolean
  openAll: boolean
  selectAll: boolean
}

//菜单树
const permission: IPermission = reactive({
  treeList: [],
  treeProps: {
    label: 'name'
  },
  linkage: true,
  openAll: false,
  selectAll: false
})

const dialogForm = reactive<Partial<MenuItemForm>>({
  id: '',
  parentId: '',
  name: '',
  sort: 1,
  type: 0, //菜单类型（0：目录；1：菜单；2：按钮）
  redirect: '', //重定向
  path: '', //路由地址
  query: '', //路由参数
  component: '', //组件路径
  parentView: 'layout', //布局方式
  cache: 1, //是否缓存（0：缓存；1：不缓存）
  visible: 0, //显示状态（0：显示；1：隐藏）
  enabled: 1, //菜单状态（0：禁用；1：启用）
  perms: '', //权限标识
  icon: '', //图标
  outerChain: false, //是否外联[若是以http/https开头的就是外联]
  isForst: false
})
onBeforeMount(() => {
  const { proxy } = getCurrentInstance() as ComponentInternalInstance
  if (proxy) {
    ;(proxy as any).getDicts([
      'system_global_status',
      'system_menu_parentview',
      'system_global_visibility',
      'system_global_cache',
      'system_global_status'
    ])
  }
  getMenuTree()
  if (dialogFormId.value) {
    getInfo()
  }
})

const getInfo = async () => {
  const menudetails = await menuInfo(dialogFormId.value)
  const {
    parentId,
    name,
    perms,
    sort,
    enabled,
    type,
    icon,
    path,
    outerChain,
    redirect,
    visible,
    component
  } = menudetails.data
  dialogForm.parentId = parentId
  dialogForm.name = name
  dialogForm.perms = perms
  dialogForm.sort = sort
  dialogForm.enabled = enabled
  dialogForm.type = type
  console.log(icon, 'icon')
  dialogForm.icon = icon
  dialogForm.path = path
  dialogForm.outerChain = outerChain
  dialogForm.redirect = redirect
  dialogForm.visible = visible
  dialogForm.component = component

  // menuTreeRef.value?.setCheckedKeys(data.permissions)
}
const getMenuTree = async () => {
  //获取权限菜单数据
  const menuData = await menuTree({
    current: '1',
    size: '999',
    enabled: '1'
  })
  let { records } = menuData.data
  permission.treeList = normalizeMenuList(records)
}

//选择以及菜单
const toggleTreeChecked = (e) => {
  console.log(e)
}

//点击切换
const cutChange = (val) => {
  dialogForm.type = val
  dialogForm.path = '' //路由地址
  dialogForm.outerChain = false //是否外联
  dialogForm.redirect = '' //重定向
  dialogForm.visible = 0 // 是否显示
  dialogForm.query = '' //路由参数
  dialogForm.cache = 1 //是否缓存
  dialogForm.component = '' //组件路径
  dialogForm.parentView = 'layout' //布局方式
  dialogForm.icon = '' //图标
  dialogForm.parentId = ''
  if (val == 0 || !dialogForm.parentId) {
    dialogForm.isForst = true
    dialogForm.parentId = '-1'
  } else {
    dialogForm.isForst = false
  }
}

const onSubmit = async () => {
  if (dialogFormId.value != '') {
    await updateRole()
  } else {
    await addRole()
  }
}

const addRole = async () => {
  if (!dialogForm.parentId) {
    dialogForm.parentId = '-1'
  }
  const res = await menuAdd({
    ...dialogForm
  })
  if (res.code === 200) {
    emit('update:dialogVisible', false)
    emit('update:dialogFormId', '')
    emit('getPage', { name: '', enabled: '', type: '' })
  }
}

const updateRole = async () => {
  const res = await menuUpdata({
    ...dialogForm,
    id: dialogFormId.value
  })
  if (res.code === 200) {
    ElMessage({
      type: 'success',
      message: '操作成功'
    })
    emit('update:dialogVisible', false)
    emit('update:dialogFormId', '')
    emit('getPage', { name: '', enabled: '', type: '' })
  }
}
const onCancel = () => {
  emit('update:dialogVisible', false)
}
</script>
